import os
import shutil
from openpyxl import load_workbook
from openpyxl.utils.exceptions import InvalidFileException
import pandas as pd
import magic
from MyException import MyException
import zipfile
# 指定原始目录和目标目录
source_directory = r'E:\工资\文件'
target_directory = r'E:\工资\加密文件'
log_info_file = []
log_info_path = []
# 确保目标目录存在，如果不存在则创建
if not os.path.exists(target_directory):
    os.makedirs(target_directory)
if not os.path.exists(source_directory):
    os.makedirs(source_directory)

def is_excel_encrypted(file_path):
    try:
        load_workbook(file_path)
        return False  # Excel文件未加密
    except InvalidFileException:
        return True  # Excel文件已加密

def is_compressed_file(file_path):
    mime = magic.Magic(mime=True)
    file_type = mime.from_file(file_path)
    return 'application/zip' in file_type or 'application/x-gzip' in file_type

# 遍历目录及其子目录下的所有Excel文件
excel_files = []
for root, dirs, files in os.walk(source_directory):
    for file in files:
        if file.endswith('.xlsx') or file.endswith('.xls'):
            excel_files.append(os.path.join(root, file))

try:
    # 打印所有Excel文件的路径
    for excel_file in excel_files:
        print(excel_file)
        if is_compressed_file(excel_file):
            continue
        # 检测Excel文件是否加密
        if is_excel_encrypted(excel_file):
        #print(f'{excel_file_path} 是加密的Excel文件')
            source_file = os.path.join(root, excel_file)
            target_file = os.path.join(source_directory, excel_file)
            # 使用shutil模块的move函数将文件剪切到目标目录
            shutil.move(source_file, target_file)
        else:
            log_info_file.append(excel_file)
            log_info_path.append(os.path.join(source_directory,excel_file))
            #log_info.append(f'{excel_file} 不是加密的Excel文件')
            # 在这里可以对每个Excel文件进行操作，例如读取内容或进行其他处理
except zipfile.BadZipFile as e:
    print(e.args)
    print('异常信息')


    


list_arr = np.array(log_info_file,log_info_path)
result_arr = np.transpose(list_arr)

file_df = pd.DataFrame(result_arr,columns=['文件名称','路径'])
file_df.to_csv('加密文件汇总表.csv')




